package com.homework.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.base.day8.JDBCComon;
import com.homework.entity.User;

public class UserService {
	JDBCComon jdbc=new JDBCComon();
	//登录
	public User login(String name,String pwd){
		User user=null;
		try {
			Connection conn=jdbc.getConnection();
			Statement st=conn.createStatement(); 
			String sql="select * from user where  name='"+name+"' and pwd='"+pwd+"'";
			System.out.println("sql--->"+sql);
			ResultSet rss=st.executeQuery(sql);
			//rss.next()只要 结果集合里，至少有一条记录，next方法就会返回true
			if(rss.next()){
				user=new User();
				user.setId(rss.getString("id"));
				user.setName(rss.getString("name"));
			}
			//从下往上关
			rss.close();
			st.close();
			conn.close();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return user;
	}
	
	//验证用户名是否存在
	public User checkName(String name){
		User user=null;
		try {
			Connection conn=jdbc.getConnection();
			Statement st=conn.createStatement(); 
			String sql="select * from user where  name='"+name+"' ";
			System.out.println("sql--->"+sql);
			ResultSet rss=st.executeQuery(sql);
			//rss.next()只要 结果集合里，至少有一条记录，next方法就会返回true
			if(rss.next()){
				user=new User();
				user.setId(rss.getString("id"));
				user.setName(rss.getString("name"));
			}
			//从下往上关
			rss.close();
			st.close();
			conn.close();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return user;
	}
	
	
		public List<User> selectAll(){
			List<User> ulist=new ArrayList();
			try {
				Connection conn=jdbc.getConnection();
				Statement st=conn.createStatement(); 
				String sql="select * from user ";
				System.out.println("sql--->"+sql);
				ResultSet rss=st.executeQuery(sql);
				//rss.next()只要 结果集合里，至少有一条记录，next方法就会返回true
				while(rss.next()){
					User user=new User();
					user.setId(rss.getString("id"));
					user.setName(rss.getString("name"));
					user.setAge(rss.getInt("age"));
					ulist.add(user);
				}
				//从下往上关
				rss.close();
				st.close();
				conn.close();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return ulist;
		}

}
